<template>
    <div class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <p>特殊房间总数量：{{total}}</p>
                <el-row>
                    <el-button type="success" @click="handleCreate">&emsp;新增&emsp;</el-button>
                    <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>

                    <el-form :inline="true" :model="searchForm" ref="searchForm" class="demo-form-inline">
                        <el-form-item label="">
                            <el-select filterable v-model="searchForm.type_id" placeholder="请选择房间类型">
                                <el-option
                                v-for="item in roomTypeOptions"
                                :key="item.id"
                                :label="item.room_type_name"
                                :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="">
                            <el-input type="text" v-model.number="searchForm.search" placeholder="房间编号/房主编号"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="searchSubmit">查询</el-button>
                            <el-button type="primary" @click="resetSubmit">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-row>
            </div>
            <div class="item" v-loading="listLoading">
                <el-table ref="dataList" :data="menuList" @selection-change="handleSelectionChange" style="width:100%;margin-bottom: 20px;" row-key="id" border :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                    <el-table-column type="selection"></el-table-column>
                    <el-table-column prop="id" label="序号"> </el-table-column>
                    <el-table-column prop="room_id" label="房间编号" > </el-table-column>
                    <el-table-column prop="user_code" label="房主ID" > </el-table-column>
                    <el-table-column prop="type_name" label="房间分类" > </el-table-column>
                    <el-table-column label="阶梯设置">
                        <template slot-scope="scope">
                            <p v-for="(item,index) in scope.row.rate" :key="index">
                                阶梯{{index+1}}：{{item.rate}}%  （{{item.coin_min}}-{{item.coin_max}}）
                            </p>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sociaty_no" label="所属公会" > </el-table-column>
                    <el-table-column prop="sociaty_name" label="公会名称" > </el-table-column>
                    <el-table-column prop="remark" label="备注" > </el-table-column>

                    <el-table-column fixed="right" label="操作" width="180px">
                        <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>编辑</el-button>
                        <!-- <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn> -->
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)" plain>删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <cus-pagination
                    :total="total"
                    :page.sync="searchForm.pageNum"
                    :limit.sync="searchForm.perPage"
                    @pagination="getList"
                />
            </div>
        </el-card>
        <!-- 删除弹框 -->
        <el-dialog
            title="确定删除吗?"
            :visible.sync="deleteDialogVisible"
            width="435px"
            >
            <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="deleteDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmDelete">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 新增编辑弹框 -->
        <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleDialogClose">
            <el-form ref="dataForm" :rules="rules" :model="dynamicValidateForm" label-position="right" label-width="80px" style="width: 400px; margin: 0 auto;">
                <el-form-item label="房间编号" prop="room_id" >
                    <el-input  v-if="this.dialogStatus === 'create'" v-model="dynamicValidateForm.room_id" @blur="handleInputRoom" placeholder="请输入房间编号"/>
                    <el-input  v-if="this.dialogStatus === 'update'" :disabled="true" v-model="dynamicValidateForm.room_id" @blur="handleInputRoom" placeholder="请输入房间编号"/>
                    <!-- <p>{{roomName}}</p> -->
                </el-form-item>
                <el-form-item v-if="this.dialogStatus === 'create'" label="房间名">
                    <el-input v-model="roomName" placeholder="房间名" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item
                    v-for="(domain, index) in dynamicValidateForm.domains"
                    :label="'阶梯' + (index+1)"
                    :key="index"
                >
                    <el-form-item
                        style="margin-bottom:22px;"
                        :prop="'domains.' + index + '.coin_min'"
                        :rules="{
                            type:'number',required: true, message: '请输入正确数字', trigger: 'blur',min:0,
                        }"
                    >
                        <el-input v-model.number="domain.coin_min" placeholder="请输入最小金币"></el-input>
                    </el-form-item>
                    <el-form-item
                        style="margin-bottom:22px;"
                        :prop="'domains.' + index + '.coin_max'"
                        :rules="{
                            type:'number',required: true, message: '请输入正确数字', trigger: 'blur',min:0,
                        }"
                    >
                        <el-input v-model.number="domain.coin_max" placeholder="请输入最大金币"></el-input>
                    </el-form-item>
                    <el-form-item
                        style="margin-bottom:22px;"
                        :prop="'domains.' + index + '.rate'"
                        :rules="{
                            type:'number',required: true, message: '请输入0-100的数字', trigger: 'blur',min:0,max:100
                        }"
                    >
                    <el-input v-model.number="domain.rate" placeholder="请输入分成比例"></el-input>
                    </el-form-item>
                    <el-button v-if="index!==0" type="danger" @click.prevent="removeDomain(domain)">删除该阶梯</el-button>
                </el-form-item>
                <el-form-item label="备注" prop="remark" >
                    <el-input v-model="dynamicValidateForm.remark"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="submitForm('dynamicValidateForm')">保存</el-button>
                    <el-button type="primary" @click="addDomain">新增阶梯</el-button>
                    <el-button type="danger" @click="cancelForm">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>

import {
    getSpecialRoom,
    getRoomType,
    getRoomName,
    postDeleteRoom,
    postAddRoom,
    postEditRoom
} from '@/api/unionWater/specialRoomList'
export default {
    data(){
        return{
            // 房间名字
            roomName:"",
            // 表单数据
            dynamicValidateForm: {
                room_id: '',
                domains: [{
                    rate:undefined,
                    coin_min:undefined,
                    coin_max:undefined
                }],
                remark:''
            },
            // 表单验证规则
            rules: {
                room_id: [{ required: true, message: '请输入房间编号', trigger: 'blur' }],
                // remark:[{}]
            },
            dialogStatus: '',
            // dialog的头部信息
            titleMap: {
                update: '编辑',
                create: '增加'
            },
            // 新增修改弹框显示
            dialogFormVisible:false,
            // 删除弹框显示
            deleteDialogVisible:false,
            specialRoomForm:[],
            listLoading:true,
            // 特殊房间总数
            total:0,
            // 房间类别
            roomTypeOptions:[],
            // 搜索表单内容
            searchForm:{
                type_id:'',
                search:'',
                pageNum:1,
                perPage:10,
            },
            // 表格列表
            menuList:[],
            // 勾选内容
            multipleSelection: [],
            // 要删除的内容的ids
            dataIds:'',
            // 存一个当前行数据
            rowData:{}

        }
    },
    created(){
        this.getList()
        this.getSpecialRoomType()
    },
    methods:{
        // 点击查询
        searchSubmit(){
            this.searchForm.pageNum=1;
            // this.searchForm.perPage=10;
            this.getList()
        },
        // 点击重置
        resetSubmit(){
            this.searchForm.pageNum=1;
            this.searchForm.perPage=10;
            this.searchForm.type_id="";
            this.searchForm.search=""
        },
        // 点击编辑
        handleUpdate(row) {

            this.resetForm()
            this.dynamicValidateForm.room_id = row.room_id;
            this.dynamicValidateForm.remark = row.remark;
            this.dynamicValidateForm.domains = JSON.parse(JSON.stringify(row.rate));
            this.handleInputRoom();

            this.dialogStatus = 'update'
            this.dialogFormVisible = true

        },
        // 点击单个删除
        handleDelete(row) {
            this.dataIds = {ids:`${row.id}`}
            this.deleteDialogVisible = true
        },
        // 点击批量删除
        handleDeleteAll(){
            if(this.multipleSelection.length === 0){
                this.$message({
                    message: '请先勾选要删除的内容',
                    type: 'warning'
                });
                return;
            }else if(this.multipleSelection.length !== 0){
                let ids = '';
                for(let key in this.multipleSelection){
                    ids+=`${this.multipleSelection[key].id},`
                }
                ids = ids.substring(0, ids.length - 1)
                this.dataIds = {ids:ids}
            }
            this.deleteDialogVisible = true
        },
        // 勾选
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 确定删除
        confirmDelete(){

            postDeleteRoom(this.dataIds).then((response) => {
                if (response.code === 200) {
                    this.getList()
                    this.deleteDialogVisible = false;
                    this.$notify({
                        type:'success',
                        message: '操作成功',
                        position: 'bottom-right',
                        showClose: false,
                        duration: 3000
                    });
                } else {
                    this.$message({
                        message: response.message,
                        type: 'error'
                    });
                }
            })
        },
        // 获取列表
        getList(){
            this.listLoading = true;
            let urlData = "?";
            if (this.searchForm.pageNum) {
                urlData = urlData + `page=${this.searchForm.pageNum}&`;
            }
            if (this.searchForm.perPage) {
                urlData = urlData + `perPage=${this.searchForm.perPage}`;
            }
            if (this.searchForm.type_id) {
                urlData = urlData + `&type_id=${this.searchForm.type_id}`;
            }
            if (this.searchForm.search) {
                urlData = urlData + `&search=${this.searchForm.search}`;
            }
            // urlData)

            getSpecialRoom(urlData).then((response) => {
                // response)
                if(response.code === 200){
                    this.menuList = response.data.list;
                    this.total = response.data.meta.total;
                    this.listLoading = false;
                }

            });
        },
        // 获取特殊房间分类
        getSpecialRoomType(){
            getRoomType().then((response) => {
                // response)
                if(response.code === 200){
                    this.roomTypeOptions = response.data;
                }
            })
        },
        // 点击新增
        handleCreate(row) {
            this.resetForm()
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
        },
        // 获取房间名
        handleInputRoom(){
            // this.dynamicValidateForm.room_id)
            if(this.dynamicValidateForm.room_id === '') return;
            let urlData = `?room_id=${this.dynamicValidateForm.room_id}`
            getRoomName(urlData).then(response => {
                this.roomName = response.data;
            }).catch(error=>{
                this.roomName = ''
            })
        },
        // 点击保存提交
        submitForm() {
            // this.roomName)
            if(this.roomName === '') {
                this.$message({
                    type:'error',
                    message:'房间不存在'
                })
                return
            }
            this.$refs['dataForm'].validate(valid => {
                if (valid && this.dialogStatus === 'create') {
                    let formData = {
                        "room_id":'',
                        "array":[],
                        "remark":''
                    }
                    formData.room_id = this.dynamicValidateForm.room_id
                    formData.remark = this.dynamicValidateForm.remark
                    this.dynamicValidateForm.domains.forEach((item,index) => {
                        // item)
                        formData.array.push(item)
                    })
                    // formData)
                    postAddRoom(formData).then(response=>{
                        // response)
                        if(response.code === 200){
                            this.getList();
                            this.$notify({
                                type:'success',
                                message: '操作成功',
                                position: 'bottom-right',
                                showClose: false,
                                duration: 3000
                            });
                            this.dialogFormVisible = false
                            this.roomName = ''
                        }else if(response.code === 30023){
                            this.$message({
                                message: response.message,
                                type: 'error'
                            })
                        }else if(response.code === 30024){
                            this.$message({
                                message: response.message,
                                type: 'error'
                            })
                        }
                    })
                }else if(valid && this.dialogStatus === 'update'){
                    let formData = {
                        "id":'',
                        "array":[],
                        "remark":''
                    }
                    formData.id = this.rowData.id
                    formData.remark = this.rowData.remark
                    this.dynamicValidateForm.domains.forEach((item,index) => {
                        formData.array.push(item)
                    })
                    // formData)
                    postEditRoom(formData).then(response=>{
                        if(response.code === 200){
                            this.getList();
                            this.$notify({
                                type:'success',
                                message: '操作成功',
                                position: 'bottom-right',
                                showClose: false,
                                duration: 3000
                            });
                            this.dialogFormVisible = false
                            this.roomName = ''
                        }else if(response.code === 30025){
                            this.$message({
                                message: response.message,
                                type: 'warning'
                            })
                        }else if(response.code === 30026){
                            this.$message({
                                message: response.message,
                                type: 'error'
                            })
                        }
                    })
                }
            })
        },
        // 取消提交
        cancelForm(){
            this.dialogFormVisible = false;
        },
        // 重置表单内容
        resetForm() {
            this.dynamicValidateForm = {
                room_id:'',
                domains:[{
                    rate:'',
                    coin_min:'',
                    coin_max:''
                }],
                remark:''
            }
        },
        // 点击删除该阶梯
        removeDomain(item) {
            let index = this.dynamicValidateForm.domains.indexOf(item)
            if (index !== -1) {
            this.dynamicValidateForm.domains.splice(index, 1)
            }
        },
        // 点击添加新阶梯
        addDomain() {
            this.dynamicValidateForm.domains.push({
                rate:'',
                coin_min:'',
                coin_max:''
            });
            // this.dynamicValidateForm)
        },
        // 监听dialog关闭时的处理事件
        handleDialogClose() {
            if (this.$refs['dataForm']) {
            this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
            }
        }
    }
}
</script>

<style scoped>
    [v-cloak] {
        display: none;
    }
    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }

    .box-card {
        width: 100%;
    }

    .demo-form-inline {
        float: right;
    }

    /deep/ .el-card__header {
        padding-bottom: 0;
    }

    .item {
        margin-bottom: 18px;
    }

    /deep/ .el-table_1_column_6 .cell{
        display: flex;
        flex-direction:column;
    }

    /deep/ .el-dialog__title {
        font-size: 14px;
    }

    /deep/ .el-dialog__body {
        border: 0;
    }
</style>
